package com.example.cxf.webservice.impl;

import com.example.cxf.model.entity.VehicleInfo;
import com.example.cxf.webservice.VehicleWebservice;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>说明：</p>
 * <p>1. @WebService 注解是必须的</p>
 * <p>2. serviceName 是必须的，表示服务的名字；该名字会拼接到服务路径的最后面；例如：http://x/xx/xxx/vehicleService?wsdl</p>
 * <p>3. targetNamespace 是必须的；可自定义(通常使用使用包名反转)；注意必须和接口中指定的 targetNamespace 一致</p>
 * <p>4. endpointInterface 是必须的，填写接口的 包名.类名 </p>
 */
@Component
@Slf4j
@WebService(serviceName = "vehicleService",
        targetNamespace = "http://vehicle.cxf.example.com", //指定你想要的名称空间，通常使用使用包名反转
        endpointInterface = "com.example.cxf.webservice.VehicleWebservice")
public class VehicleWebserviceImpl implements VehicleWebservice {

    private static final Map<String, VehicleInfo> vehicleMap = new HashMap<String, VehicleInfo>();

    private static final AtomicInteger vehicleCounter = new AtomicInteger(0);

    static {
        VehicleInfo v1 = new VehicleInfo();
        v1.setId(vehicleCounter.incrementAndGet() + "");
        v1.setPlatesNumber("湘A11111");
        v1.setRegisterDate(new Date());
        v1.setCreateTime(new Date());
        vehicleMap.put(v1.getId(), v1);

        VehicleInfo v2 = new VehicleInfo();
        v2.setId(vehicleCounter.incrementAndGet() + "");
        v2.setPlatesNumber("湘A22222");
        v2.setRegisterDate(new Date());
        v2.setCreateTime(new Date());
        vehicleMap.put(v2.getId(), v2);

        log.info("vehicleMap: {}", vehicleMap);
    }

    public VehicleInfo getVehicleInfo(String id) {
        return vehicleMap.get(id);
    }

    @Synchronized
    public Boolean saveVehicleInfo(VehicleInfo vehicleInfo) {
        boolean existed = vehicleMap.values().stream().anyMatch(v -> v.getPlatesNumber().equals(vehicleInfo.getPlatesNumber()));
        if (existed) {
            log.info("车牌号 {} 已存在！", vehicleInfo.getPlatesNumber());
            return false;
        }
        int id = vehicleCounter.incrementAndGet();
        vehicleInfo.setId(id + "");
        log.info("saveVehicleInfo: {}", vehicleInfo);
        vehicleMap.put(vehicleInfo.getId(), vehicleInfo);
        return true;
    }
}
